#include "LivingEntity.h"

LivingEntity::LivingEntity(const std::map<std::string, BornedNumber<double> >& attr, int life, int min, int max): Entity(), life__(life, min, max)
{
	attributes__ = attr;
	underAttack__ = false ;
	timeCounter__ = 0 ;
	// note that this constructor doesn't sets the defaults attributes
}

LivingEntity::LivingEntity(int life, int min, int max): Entity(), life__(life, min, max)
{
	// Have some default attributes
	attributes__["speed"] = BornedNumber<double>(400, 400, 0);
	attributes__["rotatespeed"] = BornedNumber<double>(180, 180, 0);
	attributes__["eatable"] = BornedNumber<double>(0, 1.0, 0); ;
	underAttack__ = false ;
}

LivingEntity::~LivingEntity()
{
}

BornedNumber<float> LivingEntity::getLife(){
     return life__;
}

bool LivingEntity::isUnderAttack()
{
     return underAttack__ ;    
}

void LivingEntity::setUnderAttack(bool status)
{
    underAttack__ = status ; 
}

bool LivingEntity::isDead()
{
	return life__ <= life__.getMin();
}

bool LivingEntity::isAlive()
{
	return !isDead();
}

bool LivingEntity::isLifeCritical()
{
	return (life__.getValue() <= life__.getMax()/6) ;
}

bool LivingEntity::addLife(float val)
{
	life__ += val;
	return isDead();
}

bool LivingEntity::removeLife(float val)
{
	life__ -= val;
	return isDead();
}

bool LivingEntity::attributeExists(const irr::core::string<c8>& attrName)
{
	return attributeExists(std::string(attrName.c_str()));
}

bool LivingEntity::attributeExists(const std::string& attrName)
{
	return attributes__.find(attrName) != attributes__.end();
}

BornedNumber<double>& LivingEntity::getAttribute(const irr::core::string<c8>& attrName)
{
	return getAttribute(std::string(attrName.c_str()));
}

BornedNumber<double>& LivingEntity::getAttribute(const std::string& attrName)
{
	return attributes__[attrName];
}

std::map<std::string, BornedNumber<double> >& LivingEntity::getAttributes()
{
	return attributes__;
}

void LivingEntity::loadAttributesFromFile(const std::string& entity_type)
{
	std::string real_path = "./baseq3/behaviours/" + entity_type + ".attr";
	std::ifstream is(real_path.c_str(), std::ios_base::in);
	if (!is.is_open())
	{
		std::cerr << "***** WARNING: Could not load attribute list from file: " << real_path << std::endl;
		return;
	}

	while (!is.eof())
	{
		std::string attrName;
		double min;
		double val;
		double max;

		is >> attrName;
		is >> min;
		is >> val;
		is >> max;

		if (attrName != "")
		{
			if (attrName == "life")
			{
				life__.setMax(max);
				life__.setMin(min);
				life__ = val;
			}
			else
			{
				BornedNumber<double> b(val, max, min);
				getAttribute(attrName) = b;
			}
		}
	}

	is.close();
}

